package com.rc.saas.tenant.controller.discount;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.TimeUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.controller.elec.ElecPileController;
import com.rc.saas.tenant.model.discount.TenantDiscountPolicy;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.service.discount.TenantDiscountMemberService;
import com.rc.saas.tenant.service.discount.TenantDiscountPolicyService;
import com.rc.saas.tenant.service.discount.TenantDiscountTimeService;
import com.rc.saas.tenant.service.elec.ElecStationPriceService;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.discount.DiscountTimeSaveVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @date 2019/11/25
 */
@Controller
@RequestMapping("/discount")
public class DiscountController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(ElecPileController.class);


    @Autowired
    private TenantDiscountPolicyService tenantDiscountPolicyService;

    @Autowired
    private TenantDiscountTimeService tenantDiscountTimeService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private TenantDiscountMemberService tenantDiscountMemberService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    /**
     * 返回优惠方案列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listDiscountPolicy", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listDiscountPolicy(BaseSearch baseSearch, Long elecStationId) {
        PageInfo<TenantDiscountPolicy> pageInfo = tenantDiscountPolicyService.searchByCondition(baseSearch, elecStationId);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转增加优惠方案页面
     *
     * @return
     */
    @RequestMapping(value = "/addDiscountPolicy/{elecStationId}", method = RequestMethod.GET)
    public String addDiscountPolicy(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/discount/addDiscountPolicy";
    }


    /**
     * 跳转编辑优惠方案页面
     *
     * @return
     */
    @RequestMapping(value = "/editDiscountPolicy/{discountPolicyId}", method = RequestMethod.GET)
    public String editDiscountPolicy(@PathVariable("discountPolicyId") Long discountPolicyId, Model model) {
        TenantDiscountPolicy tenantDiscountPolicy = tenantDiscountPolicyService.selectAllById(discountPolicyId);
        model.addAttribute("tenantDiscountPolicy", tenantDiscountPolicy);
        return "/templates/discount/editDiscountPolicy";
    }


    /**
     * 获取编辑优惠方案数据
     *
     * @return
     */
    @RequestMapping(value = "/getDiscountPolicyData", method = RequestMethod.GET)
    public TResponse getDiscountPolicyData(Long discountPolicyId) {
        TenantDiscountPolicy tenantDiscountPolicy = tenantDiscountPolicyService.selectAllById(discountPolicyId);
        return TResponse.SUCCESS_DATA(tenantDiscountPolicy);
    }


    /**
     * 跳转查看优惠方案页面
     *
     * @return
     */
    @RequestMapping(value = "/detailDiscountPolicy/{discountPolicyId}", method = RequestMethod.GET)
    public String detailDiscountPolicy(@PathVariable("discountPolicyId") Long discountPolicyId, Model model) {
        TenantDiscountPolicy tenantDiscountPolicy = tenantDiscountPolicyService.selectAllById(discountPolicyId);
        ElecStation elecStation = elecStationService.selectByPrimaryKey(tenantDiscountPolicy.getElecStationId());
        model.addAttribute("stationName", elecStation.getStationName());
        model.addAttribute("tenantDiscountPolicy", tenantDiscountPolicy);
        return "/templates/discount/detailDiscountPolicy";
    }


    /**
     * 保存编辑优惠方案
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateDiscountPolicy", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateDiscountPolicy(TenantDiscountPolicy tenantDiscountPolicy) {

        TenantUser user = ShiroUtils.getSessionUser();

        if (!BeanUtil.isValid(tenantDiscountPolicy.getPolicyName(), tenantDiscountPolicy.getDiscountType(),
                tenantDiscountPolicy.getBeginTime(), tenantDiscountPolicy.getEndTime())) {
            return TResponse.FAIL("请输入正确的参数");
        }

        try {

            tenantDiscountPolicy.setLastUpdatedBy(user.getLoginName());
            tenantDiscountPolicy.setLastUpdatedTime(new Date());
            if (tenantDiscountPolicy.getDiscountPolicyId() == null) {
                tenantDiscountPolicy.setTenantCode(user.getTenantCode());
                //设置状态为默认  默认为禁止状态
                tenantDiscountPolicy.setStatus("3");
                //设置默认为全部用户
                tenantDiscountPolicy.setPolicyMemberType("0");
                //设置默认为全天
                tenantDiscountPolicy.setTimeType(0);
                tenantDiscountPolicyService.insertReturnPrimaryKey(tenantDiscountPolicy);
            } else {
                tenantDiscountPolicyService.updateByPrimaryKeySelective(tenantDiscountPolicy);
            }
            return TResponse.SUCCESS_DATA(tenantDiscountPolicy);
        } catch (Exception e) {
            logger.error("保存优惠方案失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存编辑优惠方案时段
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateDiscountTime", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateDiscountTime(@RequestBody String tenantDiscountTime) {
        TenantUser user = ShiroUtils.getSessionUser();

        try {
            String timeType = JSONObject.parseObject(tenantDiscountTime).getString("timeType");
            String discountType = JSONObject.parseObject(tenantDiscountTime).getString("discountType");
            Long discountPolicyId = JSONObject.parseObject(tenantDiscountTime).getLong("discountPolicyId");
            Long elecStationId = JSONObject.parseObject(tenantDiscountTime).getLong("elecStationId");


            if (!BeanUtil.isValid(timeType, discountType, discountPolicyId, elecStationId)) {
                return TResponse.FAIL("请输入正确的参数");
            }

            //全天
            if ("1".equals(timeType)) {
                BigDecimal elecPrice = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("elecPrice");
                BigDecimal servicePrice = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("servicePrice");
                BigDecimal discount = JSONObject.parseObject(tenantDiscountTime).getBigDecimal("discount");

                tenantDiscountTimeService.insertDiscountTime(discountPolicyId, elecStationId, discountType, timeType, elecPrice, servicePrice, discount, null, user.getTenantCode());
            } else {
                List<DiscountTimeSaveVo> discountTimeSaveVoList = JSONObject.parseArray(JSONObject.parseObject(tenantDiscountTime).getString("discountTimeSaveVoList"), DiscountTimeSaveVo.class);

                List<String> list = new ArrayList<String>();
                for (DiscountTimeSaveVo discountTimeSaveVo : discountTimeSaveVoList) {
                    list.add(discountTimeSaveVo.getStartPeriod() + "-" + discountTimeSaveVo.getEndPeriod());
                }

                // Boolean overlappTime = tenantDiscountTimeService.isOverlappTime(discountTimeSaveVoList);
                Boolean overlappTime = TimeUtil.isOverlappTime(list);

                if (overlappTime == true) {
                    return TResponse.FAIL("时间重叠");
                }

                tenantDiscountTimeService.insertDiscountTime(discountPolicyId, elecStationId, discountType, timeType, null, null, null, discountTimeSaveVoList, user.getTenantCode());
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存优惠时段失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存编辑优惠方案会员
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateDiscountMember", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateDiscountMember(@RequestBody String tenantDiscountMember) {
        TenantUser user = ShiroUtils.getSessionUser();

        try {
            String memberType = JSONObject.parseObject(tenantDiscountMember).getString("memberType");
            Long discountPolicyId = JSONObject.parseObject(tenantDiscountMember).getLong("discountPolicyId");
            TResponse tResponse = new TResponse();
            if ("1".equals(memberType)) {
                String StringList = JSONObject.parseObject(tenantDiscountMember).getString("list");
                tResponse = tenantDiscountMemberService.insertDiscountMember(user.getTenantCode(), memberType, discountPolicyId, StringList);
            } else {
                tResponse = tenantDiscountMemberService.insertDiscountMember(user.getTenantCode(), memberType, discountPolicyId, null);
            }
            if (tResponse != null) {
                return tResponse;
            } else {
                return TResponse.SUCCESS();
            }
        } catch (Exception e) {
            logger.error("保存优惠方案会员失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 禁止方案
     *
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateStatus(Long discountPolicyId) {
        try {
            TResponse tResponse = tenantDiscountPolicyService.updateStatus(discountPolicyId);
            return tResponse;
        } catch (Exception e) {
            logger.error("禁止方案失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 判断是否有进行中的方案
     *
     * @return
     */
    @RequestMapping(value = "/isUsingPolicy", method = RequestMethod.GET)
    @ResponseBody
    public TResponse isUsingPolicy(Long elecStationId) {
        try {
            TResponse tResponse = tenantDiscountPolicyService.isUsingPolicy(elecStationId, null);
            return tResponse;
        } catch (Exception e) {
            logger.error("判断进行中的方案失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

}
